package com.cdshangpai.utils.storage;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.Log;

import com.cdshangpai.PhotoappApplication;
import com.cdshangpai.photoapp.LogConfig;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 图片管理工具
 */
public class ImageManager {
    public static final byte[] encryptionbuf="#￥@……&*（——@！".getBytes();
    public static String imageBaseFolder=FileConfig.baseFolder+File.separator+FileConfig.baseFolder+File.separator+FileConfig.imageFolder;

    /**
     * 下载图片文件
     * @param url
     * @return
     */
    public String download(String url)
    {
        BlockingQueue<String> queue=new LinkedBlockingDeque<>();
        DownloadListenter listenter=new DownloadListenter(queue);
        DownloadUtil.get().download(url,imageBaseFolder,true,listenter);
        String fileName=null;
        try{
            fileName=queue.take();
//            Log.i(LogConfig.logTag,"下载成功，文件位置:"+fileName);
        }catch (InterruptedException e){
            Log.i(LogConfig.logTag,"从下载对象获取文件名出现异常");
        }
        return fileName;
    }

    /**
     * 批量删除图片
     * @param fileNameList
     */
    public void deleteImages(String fileNameList)
    {
        if(TextUtils.isEmpty(fileNameList))
        {
            return;
        }
        String[] files=fileNameList.split(",");
        for(String file:files)
        {
            delete(file);
        }
    }

    /**
     * 删除图片文件
     * @param fileName
     */
    public void delete(String fileName)
    {
        FileInput fi=new FileInput(PhotoappApplication.context);
        fi.delete(imageBaseFolder,fileName);
    }

    /**
     * 加载图片文件二进制数据
     * @param fileName 图片文件名称
     * @return  图片文件二进制数据
     * @throws IOException
     */
    public byte[] loadImageByte(String fileName) throws IOException
    {
        FileInput fi=new FileInput(PhotoappApplication.context,imageBaseFolder,fileName);
        /*File file=new File(imageBaseFolder,fileName);
        if(!file.exists())
        {
            return null;
        }
        int fileLength=(int)file.length();
        byte[] fileContent=new byte[fileLength];
        FileInputStream fis=new FileInputStream(file);
        fis.read(fileContent,0,fileLength);
        fis.close();*/
        byte[] fileContent=new byte[fi.getFileLenght()];
        fi.read(fileContent);
        return fileContent;
    }

    public Bitmap loadImageToBitmap(String fileName,Integer maxWidth)
    {
        try{
            byte[] data=loadImageByte(fileName);
            int offset=encryptionbuf.length;
            int length=data.length-offset;

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig= Bitmap.Config.RGB_565;
            options.inJustDecodeBounds = false;
            options.inSampleSize=1;
            Bitmap res=BitmapFactory.decodeByteArray(data,offset,length,options);
            if(res==null)
            {
                return null;
            }
            if(res.getWidth()<=maxWidth)
            {
                return res;
            }


            /*Bitmap bitmap = Bitmap.createBitmap(1000, 600, Bitmap.Config.ARGB_8888);
            Canvas canvas=new Canvas(bitmap);
            canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG));
            Rect sou=new Rect(0,0,res.getWidth(),res.getHeight());
            Rect desc=new Rect(0,0,1000,600);
            canvas.drawBitmap(res,sou,desc,new Paint());
            if(true)
            {
                return bitmap;
            }*/




            int size=((Float)((float)res.getWidth()/(float)maxWidth)).intValue();
            options.inSampleSize=size;
            options.inJustDecodeBounds =false;
            Bitmap result=BitmapFactory.decodeByteArray(data,offset,length,options);
            return result;
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 加载图片文件到Bitmap对象
     * @param fileName
     * @return
     */
    public Bitmap loadImageToBitmap(String fileName)
    {
        try{
            byte[] fileContent=loadImageByte(fileName);
            if(fileContent==null||fileContent.length==0)
            {
                return null;
            }
            Bitmap bitmap=decrypt(fileContent);
            return bitmap;
        }catch (IOException ioe)
        {
            return null;
        }
    }

    /**
     * 解码加密图片到Bitmap
     * @param source
     * @return
     */
    public Bitmap decrypt(byte[] source)
    {
        int offset=encryptionbuf.length;
        int slen=source.length;
        int elen=encryptionbuf.length;
        int length=source.length-encryptionbuf.length;
        Bitmap bitmap=BitmapFactory.decodeByteArray(source,offset,length);
        return bitmap;
    }

    /**
     * 图片缩小
     * @param bitmap
     * @param maxWidth
     * @return
     */
    public Bitmap scale(Bitmap bitmap, Integer maxWidth)
    {
        if(bitmap==null)
        {
            return bitmap;
        }
        Integer width=bitmap.getWidth();
        Integer height=bitmap.getHeight();
        Float lv=1F;
        if(width>maxWidth)
        {
            lv=new Float(maxWidth)/new Float(width);
        }
        else
        {
            return bitmap;
        }

        Matrix matrix = new Matrix();
        matrix.postScale(lv, lv);
        Bitmap newbm = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,true);
        return newbm;
    }


    public Bitmap scale_test(Bitmap source,int targetWidth) {
        if(source==null)
        {
            return source;
        }
        if(source.getWidth()==0){
            return source;
        }

        //如果图片小于设置的宽度，则返回原图
        if(source.getWidth()<targetWidth){
            return source;
        }else{
            //如果图片大小大于等于设置的宽度，则按照设置的宽度比例来缩放
            double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
            int targetHeight = (int) (targetWidth * aspectRatio);
            if (targetHeight != 0 && targetWidth != 0) {
                Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
                if (result != source) {
                    // Same bitmap is returned if sizes are the same
                    source.recycle();
                }
                return result;
            } else {
                return source;
            }
        }
    }
}
